<template>
  <upload-excel :onSuccess="onSuccess"></upload-excel>
</template>

<script setup>
import {} from 'vue'
import UploadExcel from '@/components/UploadExcel'
import { USER_RELATIONS, formatDate } from './utils'
import { userBatchImport } from '@/api/user-manage'
import { useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const i18n = useI18n()
const router = useRouter()
const onSuccess = async ({ header, results }) => {
  const uploadData = generateData(results)
  await userBatchImport(uploadData).then((res) => {
    if (res.failCount > 0) {
      ElMessage.error(
        i18n.t('msg.excel.total') +
          res.total +
          i18n.t('msg.excel.successCount') +
          res.successCount +
          i18n.t('msg.excel.failCount') +
          res.failCount +
          i18n.t('msg.excel.failList') +
          res.failNameList
      )
    } else {
      ElMessage.success(
        i18n.t('msg.excel.total') +
          res.total +
          i18n.t('msg.excel.successCount') +
          res.successCount
      )
    }

    router.push('/user/manage')
  })
}

const generateData = (results) => {
  console.log('item', results)
  const arr = []
  results.forEach((item) => {
    console.log('item', item)
    const userInfo = {}
    Object.keys(item).forEach((key) => {
      if (USER_RELATIONS[key] === 'createTime') {
        userInfo[USER_RELATIONS[key]] = formatDate(item[key])
        return
      }
      userInfo[USER_RELATIONS[key]] = item[key]
    })
    arr.push(userInfo)
  })
  return arr
}
</script>

<style lang="scss" scoped></style>
